package com.zyl.basis.syn;

/**
 * @author zhaoyl
 * @date 2024/5/27 16:57
 * @description 说明
 *
 * 两个人去银行取钱，账户
 */
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(200,"易方达理财基金");
        Drawing SP = new Drawing(account, 50, "腾讯视频VIP充值");
        Drawing YX = new Drawing(account, 100, "游戏充值");

        SP.start();
        YX.start();
    }
}

//账户

class Account{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class Drawing extends Thread{
    //账户
    Account account;
    //取了多少钱
    int drawingMoney;
    //现在手里有多少钱
    int nowMoney;
    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    @Override
    public void run() {
        //同步代码块
        //  synchronized (Drawing.class){
            synchronized (account){
            //判断有没有钱
            if (account.money-drawingMoney<0){
                System.out.println(this.getName()+"钱不够，取不了");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            //卡内余额 = 余额 - 你取的钱
            account.money = account.money - drawingMoney;
            //你手里剩的钱
            nowMoney = nowMoney + drawingMoney;


            //Thread.currentThread().getName() = this.getName();
            System.out.println(Thread.currentThread().getName()+"花费的钱"+nowMoney);
            System.out.println(account.name+"余额为"+account.money);
        }

    }
}
